<?php

/*
 *
 * @authors : IT123编程社区-mastudy
 * @email  :admin@it123.org
 * @bbs http://www.it123.org
 *  @link http://www.it123.org
 *  @Powered By  ©2016 www.it123.org[IT123编程社区]
 */

class ToolsAction extends PublicAction {

        public static function encrypt($str) {
                $salt = "www.it123.org:qq1261639911";
                $str = md5($salt . $str);
                $str = md5($salt . $str);
                $str = md5($salt . $str);
                return $str;
        }

        public static function require_check($filename) {
                if (!file_exists($filename)) {

                        die('文件' . $filename . '不存在！');
                }


                return require_once($filename);
        }

        public static function getUserWxpayimg($uid, $type = 180) {


                $db = M('member_ccount');


                $where['ccount_member_id'] = $uid;



                $res = $db->where($where)->getField('ccount_img_wxpay');



                if ($res == 1) {



                        $url = __ROOT__ . '/Data/Uploads/Userpayimg/Userwxpay_' . $uid . '_' . $type . '.jpg';





                        $path = APP_PATH . 'Data/Uploads/Userpayimg/Userwxpay_' . $uid . '_' . $type . '.jpg';


                        if (!file_exists($path)) {
                                $url = "__ROOT__/Data/Common/Images/wxpay_pic.png";
                        }
                } else {


                        $url = "__ROOT__/Data/Common/Images/wxpay_pic.png";
                }

                return $url;
        }

        public static function getArticleThumb($item) {


                $DB = M('article');
                
                
                
                $where['article_id'] = $item;
                
                
                

                $article_thumb = $DB->where($where)->getField('article_thumb');

                if ($article_thumb == '') {

                      $url=  __ROOT__.'/Data/Common/Images/ArticleThumb.jpg';
                }


                $path = APP_PATH . '/Data/Uploads/Article/' . $article_thumb;




                if (!file_exists($path)) {

                           $url=  __ROOT__.'/Data/Common/Images/ArticleThumb.jpg';
                } else {

                        $url== __ROOT__.'/Data/Uploads/Article/' . $article_thumb;
                }


                return $url;
        }

        public static function getUserAlpayimg($uid, $type = 180) {


                $db = M('member_ccount');


                $where['ccount_member_id'] = $uid;


                $res = $db->where($where)->getField('ccount_img_alipay');


                if ($res == 1) {



                        $url = __ROOT__ . '/Data/Uploads/Userpayimg/Userpay_' . $uid . '_' . $type . '.jpg';


                        $path = APP_PATH . 'Data/Uploads/Userpayimg/Userpay_' . $uid . '_' . $type . '.jpg';


                        if (!file_exists($path)) {
                                $url = "__ROOT__/Data/Common/Images/alipay_pic.png";
                        }
                } else {


                        $url = "__ROOT__/Data/Common/Images/alipay_pic.png";
                }

                return $url;
        }

        public static function updateUserpayimg($uid, $type = 'alipay') {


                $db = M('member_ccount');
                $where['ccount_member_id'] = $uid;

                if ($type == 'wxpay') {

                        $db->where($where)->setField('ccount_img_wxpay', 1);
                } else {
                        $db->where($where)->setField('ccount_img_alipay', 1);
                }
        }

        public static function getItemTagsList($module_id, $item_id) {




                if ($module_id == 2) {

                        $tagsDB = M('tags');

                        $where['tags_item_id'] = $item_id;
                        $where['tags_module_id'] = $module_id;



                        $list = $tagsDB->where($where)->select();


                        foreach ($list as $k => $v) {


                                $html = $html . '      <a class=tag  href=' . __ROOT__ . '/Tag/' . $list[$k]['tags_item_title'] . '>' . $list[$k]['tags_item_title'] . '</a>';
                        }

                        return $html;
                }
        }

        public static function recordSearchWord($data_search) {


                if (!$data_search) {

                        return FALSE;
                }



                $searchDB = M('search');

                $data_search['search_keywords'] = $keywords;
                $data_search['search_uid'] = $uid;
                $data_search['search_time'] = time();


                $searchDB->add($data_search);
        }

//超过一天不能修改



        public static function is_CanUpdatEdit($publishtime) {

                $timeline = 24 * 60 * 60; //24小时

                if ((time() - $publishtime) > $timeline) {
                        return FALSE;
                } else {
                        return TRUE;
                }
        }

        public static function is_null_face($uid) {


                $res = self::getUserinfo($uid, 'member_up_face');


                if ($res != 1) {
                        return FALSE;
                } else {
                        return TRUE;
                }
        }

        public static function getItemCollectionCount($item_id, $module_id) {

                $cDB = M('collection');






                $where['collection_item_id'] = $item_id;

                $where['collection_module_id'] = $module_id;


                $num = $cDB->where($where)->count();

                return $num;
        }

        public static function add_Collection($uid, $item_id, $module_id) {



                $cDB = M('collection');






                $where['collection_item_id'] = $item_id;

                $where['collection_module_id'] = $module_id;
                $where['collection_uid'] = $uid;

                $num = $cDB->where($where)->count();

                if ($num > 0) {

                        return 2;
                } else {


                        $where['collection_time'] = time();

                        $res = $cDB->add($where);


                        if ($res) {

                                return TRUE;
                        } else {
                                return FALSE;
                        }
                }
        }

        public static function add_Follower($uid, $fuid) {





                $fansDB = M('fans');

                $where['fans_follower_uid'] = $fuid;
                $where['fans_uid'] = $uid;



                $num = $fansDB->where($where)->count();

                if ($num > 0) {

                        return 2;
                } else {

                        $where['fans_time'] = time();



                        if ($fansDB->add($where)) {

                                return TRUE;
                        } else {
                                return FALSE;
                        }
                }
        }

        public static function is_null_nickname($uid) {


                $res = self::getUserinfo($uid, 'member_nickname');


                if (!$res) {

                        return FALSE;
                } else {
                        return TRUE;
                }
        }

        public static function getModuleLikesLists($module_id, $item_id) {

                $likeDB = M('like');

                $where['like_module_id'] = $module_id;
                $where['like_item_id'] = $item_id;

                $listlikeads = $likeDB->where($where)->getField('like_member_id', TRUE);
                $listlike = ToolsAction::GetUserInfoByIDS($listlikeads);




                return $listlike;
        }

        public static function TopTags($num) {




                $tagsDB = M('tags');



//  $alltagsNumbers = $tagsDB->count();

                $list = $tagsDB->getField('tags_item_title', TRUE);

                foreach ($list as $key => $val) {
                        $list[$key] = strtolower($val);
                }

                $list = array_unique($list);


                foreach ($list as $k => $v) {

                        $where['tags_item_title'] = $list[$k];
                        $numbers = $tagsDB->where($where)->count();

                        $tags_info[$k]['title'] = $v;
                        $tags_info[$k]['numbers'] = $numbers;



//   $tags_info[$k]['percent'] = round(($numbers / $alltagsNumbers) * 100, 1);
                }




                $tags_info = ToolsAction::myArraysort($tags_info, 'numbers', 'desc');


                $tags_info = array_slice($tags_info, 0, $num);


                return $tags_info;
        }

        public static function array_unique($data = array()) {
                $tmp = array();
                foreach ($data as $key => $value) {
//把一维数组键值与键名组合
                        foreach ($value as $key1 => $value1) {
                                $value[$key1] = $key1 . '_|_' . $value1; //_|_分隔符复杂点以免冲突
                        }
                        $tmp[$key] = implode(',|,', $value); //,|,分隔符复杂点以免冲突
                }

//对降维后的数组去重复处理
                $tmp = array_unique($tmp);

//重组二维数组
                $newArr = array();
                foreach ($tmp as $k => $tmp_v) {
                        $tmp_v2 = explode(',|,', $tmp_v);
                        foreach ($tmp_v2 as $k2 => $v2) {
                                $v2 = explode('_|_', $v2);
                                $tmp_v3[$v2[0]] = $v2[1];
                        }
                        $newArr[$k] = $tmp_v3;
                }
                return $newArr;
        }

        public static function ressetComment($list) {





                if ($list) {


                        foreach ($list as $k => $v) {





                                $list[$k]['comment_text'] = htmlspecialchars_decode($list[$k]['comment_text']);


                                $list[$k]['comment_author'] = ToolsAction::getUserinfo($list[$k]['comment_uid'], 'member_nickname');

                                $list[$k]['comment_author_face32'] = ToolsAction::getUserFace($list[$k]['comment_uid'], '32');
                                $list[$k]['comment_time'] = date('Y-m-d', $list[$k]['comment_time']);
                        }
                }

                return $list;
        }

        public static function getUserComments($uid) {

                $cDB = M('comment');

                $where['comment_uid'] = $uid;
                $where['comment_verifystatus'] = 1;

                $num = $cDB->where($where)->count();

                return $num;
        }

        public static function getUrlContent($url) {

                $ch = curl_init();
                $timeout = 10; // set to zero for no timeout  
                curl_setopt($ch, CURLOPT_URL, $url);
                curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
                curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/34.0.1847.131 Safari/537.36');
                curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
                $html = curl_exec($ch);
                echo $html;
        }

        public static function getUserFace($uid, $type) {


                if ($uid == null) {

                        return FALSE;
                }

                $mDB = M('member_basic');



                $where['member_id'] = $uid;
                $info = $mDB->where($where)->field('member_up_face')->find();

                if ($info['member_up_face'] == 1) {


                        $url = __ROOT__ . '/Data/Uploads/Face/face_' . $uid . '_' . $type . '.jpg';

                        $path = APP_PATH . 'Data/Uploads/Face/face_' . $uid . '_' . $type . '.jpg';


                        if (!file_exists($path)) {
                                $url = __ROOT__ . '/Data/Uploads/Face/face' . $type . '.jpg';
                        }
                } else {


                        $url = __ROOT__ . '/Data/Uploads/Face/face' . $type . '.jpg';
                }


                return $url;
        }

        public static function GetUserInfoByIDS($ids) {

                if (is_array($ids)) {



                        foreach ($ids as $k => $v) {

                                $list[$k]['member_nickname'] = self::getUserinfo($ids[$k], 'member_nickname');
                                $list[$k]['member_id'] = $ids[$k];
                                $list[$k]['face_32'] = ToolsAction::getUserFace($ids[$k], '32');
                        }
                }



                return $list;
        }

        public static function getUserCcountInfo($uid) {

                $cDB = M('member_ccount');

                $where['ccount_member_id'] = $uid;


                $info = $cDB->where($where)->field('ccount_points')->find();

                return $info['ccount_points'];
        }

        public static function checkLogin() {

                $uid = session('member.member_id');





                if (!$uid) {


                        return FALSE;
                } else {
                        return $uid;
                }
        }

        public static function getUserLoginInfo($user_id) {


                $recordDB = M('login_record');


                $where['record_member_id'] = $user_id;

                $num = $recordDB->where($where)->count();


                return $num;
        }

        public static function getUserAllLikesNO($user_id, $module_id) {





                if ($module_id == 1) {





                        $num = self::getUserALLArticlelikesNO($user_id);



                        return $num;
                }

                if ($module_id == 2) {


                        $num = self::getUserALLAsklikesNO($user_id);




                        return $num;
                }

                if ($module_id == 3) {


                        $num = self::getUserALLAnswerlikesNO($user_id);




                        return $num;
                }



                if ($module_id == 5) {


                        $num = self::getUserALLTopiclikesNO($user_id);




                        return $num;
                }




                if ($module_id == 6) {


                        $num = self::getUserALLPostlikesNO($user_id);




                        return $num;
                }





                if ($module_id == 7) {


                        $num = self::getUserALLHeartenlikesNO($user_id);




                        return $num;
                }






//    self::getALLArticlelikesNO();
        }

        public static function getUserALLAsklikesNO($user_id) {



//求出用户的列表ids

                $ask_ids = self::getUserAskInfo($user_id, 'ask_ids');


                if ($ask_ids) {

                        foreach ($ask_ids as $k => $value) {


                                $num = $num + self::getModuleItimlikes($ask_ids[$k], 2);
                        }

                        return $num;
                } else {
                        return 0;
                }



//     $articleDB->where($articleDB)->
        }

        public static function getUserALLArticlelikesNO($user_id) {



//求出用户的列表ids

                $article_ids = self::getUserArticleInfo($user_id, 'article_ids');




                foreach ($article_ids as $k => $value) {


                        $num = $num + self::getModuleItimlikes($value, 1);
                }

                return $num;

//     $articleDB->where($articleDB)->
        }

        public static function getUserArticleInfo($user_id, $type) {




                $articleDB = M('article');



                if ($type == 'AllArticleCount') {

                        $where['article_author_id'] = $user_id;
                        $where['article_verifystatus'] = 1;
                        $where['article_show'] = 1;
                        $where['article_ispubish'] = 1;



                        $nums = $articleDB->where($where)->count();


                        if (!$nums) {


                                return 0;
                        } else {
                                return $nums;
                        }
                }


                if ($type == 'AllArticleVisitsCount') {

                        $where['article_author_id'] = $user_id;
                        $where['article_verifystatus'] = 1;
                        $where['article_show'] = 1;
                        $where['article_ispubish'] = 1;

                        $arr = $articleDB->where($where)->getField('article_visits', TRUE);







                        foreach ($arr as $k => $v) {

                                $nums = $nums + $arr[$k];
                        }





                        return $nums;
                }


                if ($type == 'AllArticleCommentsCount') {



                        return $nums;
                }

                if ($type == 'article_ids') {



                        $where['article_author_id'] = $user_id;
                        $where['article_verifystatus'] = 1;
                        $where['article_show'] = 1;
                        $where['article_ispubish'] = 1;


                        $arr = $articleDB->where($where)->getField('article_id', TRUE);


                        return $arr;
                }
        }

        public static function deleteArr($arr, $del_value) {



                unset($arr[array_search($del_value, $arr)]); //利用unset删除这个元素

                return $arr;
        }

//创建订单编号函数
        public static function orderSN() {

                return date('YmdHis') . rand(111, 999);
        }

        public static function resMemberLists($list) {


                if ($list) {


                        foreach ($list as $k => $v) {

                                $list[$k]['member_regtime'] = date('Y-m-d H:m:s', $list[$k]['member_regtime']);
                                $list[$k]['member_logins'] = ToolsAction::getUserLoginInfo($list[$k]['member_id']);
                        }
                }

                return $list;
        }

        public static function createOrder($order_type, $price, $customer_id, $goods_id, $module_id, $order_desc) {



                $orderDB = M('order');




                $where['order_customer_id'] = $customer_id;


                $where['order_goods_id'] = $goods_id;

                $where['order_goods_module'] = $module_id;

                $info = $orderDB->where($where)->find();

                if ($info) {
                        return $info['order_id'];
                }



                $data['order_goods_price'] = $price;
                $data['order_sn'] = time();
                $data['order_customer_id'] = $customer_id;
                $data['order_pay_status'] = 1;
                $data['order_goods_id'] = $goods_id;
                $data['order_goods_module'] = $module_id;
                $data['order_desc'] = $order_desc;
                $data['order_type'] = $order_type;



                $data['order_addtime'] = time();


                $order_id = $orderDB->add($data);


                if ($order_id) {

                        return $order_id;
                } else {
                        return FALSE;
                }
        }

        public static function createCcount($uid = null) {


                if ($uid == null) {

                        return FALSE;
                }



                $ccountDB = M('member_ccount');

                $where['ccount_member_id'] = $uid;

                $num = $ccountDB->where($where)->count();


                if ($num > 0) {

                        return TRUE;

                        die();
                }




                $data['ccount_member_id'] = $uid;
                $data['ccount_points'] = 0;



                $ccount_id = $ccountDB->add($data);

                if ($ccount_id) {
                        return TRUE;
                } else {

                        return FALSE;
                }
        }

        public static function getItemCommentInfo($item_id, $module_id, $type = 'list', $pid = 0) {



                $commentDB = M('comment');

                $where['comment_item_id'] = $item_id;

                $where['comment_module_id'] = $module_id;

                $where['comment_pid'] = $pid;



                if ($type == 'list') {

                        $commentList = $commentDB->where($where)->order('comment_time desc')->select();

                        return $commentList;
                }




                if ($type == 'count') {

                        $num = $commentDB->where($where)->count();

                        return $num;
                }
        }

        public static function resetLoginRecord($data) {



                if (is_array($data)) {

                        foreach ($data as $k => $v) {



                                $data[$k]['record_time'] = date('Y-m-d H:i:s', $data[$k]['record_time']);
                        }


                        return $data;
                } else {
                        return FALSE;
                }
        }

        public static function cleanMember() {


                $memberDB = M('member_basic');

                $where['member_regtime'] = array('LT', (time() - 60 * 60 * 1));

                $where['member_accountstatus'] = 0;

                $memberDB->where($where)->delete($where);
        }

        public static function url_exists($url) {
                $ch = curl_init();
                curl_setopt($ch, CURLOPT_URL, $url);
                curl_setopt($ch, CURLOPT_NOBODY, 1); // 不下载     
                curl_setopt($ch, CURLOPT_FAILONERROR, 1);
                curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
                return (curl_exec($ch) !== false) ? true : false;
        }

//标签入库
        public static function addTags($item_id = NULL, $module_id, $tags = NULL) {
                $tags_array = explode('#', $tags);




                for ($i = 0; $i < count($tags_array); $i++) {

                        $tags_array[$i] = trim($tags_array[$i]);

                        if ($tags_array[$i] != '') {
                                $data[$i]['tags_module_id'] = $module_id;
                                $data[$i]['tags_item_id'] = $item_id;
                                $data[$i]['tags_item_title'] = $tags_array[$i];
                        }
                }

//全部插入成功，返回第一条插入成功的数据的自增ID；有一条失败就全部失败，返回false，



                return M('tags')->addAll($data);
        }

        /**
         * 查找list中找寻id等于pid的数组项，并返回
         * @param  [type] $list  [description]
         * @param  [type] $cmtpid [description]
         * @return [type]        [description]
         */
        public static function findParentCmt($list, $cmtpid) {
                foreach ($list as $key => $value) {
                        if ($value['comment_id'] == $cmtpid) {
                                /* 用数组的方式来保存所有引用的评论 */
                                global $temp_arr;
                                $temp_arr[] = $list[$key];
//p($list[$key]);echo "<hr>";
                                return $list[$key];
                        }
                }
                return false;
        }

        /*
          把temp_arr数组中保存的引用评论信息转换为html形式
         */

        public static function getChildComment($temp_arr) {
                $htmlStr = '';
                if (!is_array($temp_arr) || empty($temp_arr)) {
                        return '';
                }
                foreach ($temp_arr as $value) {
                        $tmp = '<div>';
                        $tmp .= $htmlStr;
                        $tmp .= '<span>' . $value['comment_uid'] . '  原贴：</span><br />' . $value['comment_text'];
                        $tmp .= '</div>';
                        $htmlStr = $tmp;
                }
                return $htmlStr;
        }

        /*
          list代表某一文章下的全部评论列表
          cmt代表当前要显示的评论
         */

        public static function addCommentNode($list, $cmt) {

                if (isset($cmt['comment_pid']) && $cmt['comment_pid'] != '0') {
                        $find = self::findParentCmt($list, $cmt['comment_pid']); //找寻id等于当前评论的pid的评论，返回数组。
// 递归调用，只要pid不为零，就加入到引用评论列表
                        self::addCommentNode($list, $find);
                } else {
                        return;
                }
        }

        /*
          把评论数组数据转换为html格式
         */

        public static function commentArr2Html($comment_arr) {
                $str = '';
                if (is_array($comment_arr) && !empty($comment_arr)) {
                        $str .= '<div id="commentHolder">';

                        foreach ($comment_arr as $key => $value) {
                                $str .= '<div class="comment">';
                                $str .= '<p class="title"><a  href="###"  aid=" ' . $value['comment_id'] . '">回复:' . $value['comment_id'] . '贴</a>';
                                $str .= '<span>' . date('Y-m-d', $value['comment_time']) . ' 发表</span> <span>用户：<a href="#">' . $value['comment_uid'] . '</a>|</span>   　　';
                                $str .= '</p>';

                                global $temp_arr;
                                $temp_arr = array();

//这里去查找当前评论下的所有引用的评论，并格式化为html字符串
                                $tmpStr = '';
                                self::addCommentNode($comment_arr, $value);




//    krsort($temp_arr); //根据key倒叙排序数组
                                $tmpStr = self::getChildComment($temp_arr); //添加所有的引用评论
                                $str .= $tmpStr;

                                $str .= "<p>" . $value['comment_text'] . "</p>";
                                $str .= '</div>';
                        }

                        $str .='</div>';
                }
                return $str;
        }

        public static function resetArticleList($data) {



                if (is_array($data)) {

                        foreach ($data as $k => $v) {

                                $data[$k]['article_desc'] = htmlspecialchars_decode($data[$k]['article_desc']);


                                $data[$k]['article_title'] = msubstr(htmlspecialchars_decode($data[$k]['article_title']), 0, 38);



                                if ($data[$k]['article_rec'] == 1) {


                                        $data[$k]['article_rec'] = "<span class='list_item_rec'></span>";

//    $data[$k]['article_title']="<span  class='glyphicon glyphicon-thumbs-up text-danger'></span>  ". $data[$k]['article_title'];
                                } else {

                                        $data[$k]['article_rec'] = '';
                                }





                                if ($data[$k]['article_price'] > 0) {


                                        $data[$k]['article_price_show'] = "<span class='text-danger'> <span class='glyphicon glyphicon-gift'></span>" . $data[$k]['article_price'] . "</span>";
                                } else {
                                        $data[$k]['article_price_show'] = "";
                                }




                                $data[$k]['article_author_face32'] = ToolsAction::getUserFace($data[$k]['article_author_id'], '32');
                                $data[$k]['article_author'] = ToolsAction::getUserinfo($data[$k]['article_uid'], 'member_nickname');



                                $data[$k]['article_time'] = date('Y-m-d', $data[$k]['article_time']);

                                $data[$k]['tags'] = ToolsAction::gettags($data[$k]['article_id'], 1);

                                $data[$k]['article_likes'] = ToolsAction::getModuleItimlikes($data[$k]['article_id'], 1);
                                $data[$k]['article_thumb'] = $data[$k]['article_thumb'] == '' ? '__ROOT__/Data/Uploads/Article/thumb.jpg' : '__ROOT__/Data/Uploads/Article/' . $data[$k]['article_thumb'];
                        }


                        return $data;
                } else {
                        return FALSE;
                }
        }

        public static function updateArticleLikes($article_id) {



                $articleDB = M('article');

                $where['article_id'] = $article_id;



                $artitle_likes = self::getModuleItimlikes($article_id, 1);



                $articleDB->where($where)->setField('article_likes', $artitle_likes);
        }

        public static function getModuleItimlikes($aid = 1, $module = 1) {



                $likeDB = M('like');

                $where['like_module_id'] = $module;
                $where['like_item_id'] = $aid;
                $num = $likeDB->where($where)->count();

                return $num;
        }

        public static function SendMail($email, $title, $text) {



                Vendor('EmpireMailer.ECMSSMail');

                return ECMSSMail::JwrToSendMail($email, $title, $text);
        }

        public static function delUser($uid = NULL) {

                if (!is_numeric($uid)) {
                        return FALSE;
                }

                $mDB = M('member_basic');

                $where['member_id'] = $uid;

                $memberinfo = $mDB->where($where)->find();

                if (!$memberinfo) {
                        return FALSE;
                }

                if ($mDB->where($where)->limit(1)->delete()) {
                        return TRUE;
                } else {
                        return FALSE;
                }
        }

        public static function getArticleinfo($id, $Field = NULL) {



                $aDB = M('article');

                $where['article_id'] = $id;
                $where['article_verifystatus'] = 1;
                $where['article_ispubish'] = 1;

                if ($Field != NULL) {

                        $fields = array('article_id', 'article_title', 'article_desc', 'article_author_id', 'article_addtime', 'article_visits');
                        if (in_array($Field, $fields)) {
                                $info = $aDB->where($where)->limit(1)->getField($Field);
                        }



                        return $info;
                } else {





                        $info = $aDB->where($where)->limit(1)->find();
                        if ($info) {
                                return $info;
                        }

                        return NULL;
                }
        }

        public static function getArticleList($limit = NULL, $order = 'article_addtime desc') {





                $articleDB = M('article');



                $where['article_verifystatus'] = 1;
                $where['article_ispubish'] = 1;
                $where['article_show'] = 1;



//$data=$cAViewDB->where($where)->select();   
//$aDB = M('article');




                $data = $articleDB->where($where)->order($order)->limit($limit)->select();





                $data = ToolsAction::resetArticleList($data);


                return $data;
        }

        public static function gettags($sid, $module_id) {
                $tagsDB = M('tags');

                $where['tags_item_id'] = $sid;
                $where['tags_module_id'] = $module_id;



                $tagslist = $tagsDB->where($where)->getField('tags_item_title', TRUE);





                if ($tagslist) {
                        return $tagslist;
                } else {
                        return FALSE;
                }
        }

//验证邮箱
        public static function IS_email($email = NULL) {

                if ($email == '') {
                        return FALSE;
                }

                if (!(is_string($email))) {
                        return FALSE;
                }



                if (!(filter_var($email, FILTER_VALIDATE_EMAIL))) {
                        return FALSE;
                }

                return TRUE;
        }

//字符串截取
        public static function cutString($str, $start, $length) {
                if (mb_strlen($str, 'utf-8') > ($start + $length)) {
                        $str = mb_substr($str, $start, $length, 'utf-8') . '...';
                } else {
                        $str = mb_substr($str, $start, $length, 'utf-8');
                }
                return $str;
        }

        public static function GetNum($string) {
                $str = ereg_replace("[^0-9]", '', $string);
// $str = ereg_replace("[ ^ 0 - 9\.-]",'',$string);
                if ($str == '') {
                        $str = 0;
                }
                return $str;
        }

        public static function varNoHtmlString($str = NULL) {
                if (empty($str))
                        return false;
                $str = strip_tags($str);
                $str = str_replace('/', "", $str);
                $str = str_replace("\\", "", $str);
                $str = str_replace(">", "", $str);
                $str = str_replace("<", "", $str);
                $val = str_replace("\t", "", $val);
                $val = str_replace(" ", "", $val);
                $val = str_replace("'", "", $val);



                $str = str_replace("script", "", $str);
                $str = str_replace("select", "", $str);
                $str = str_replace("join", "", $str);
                $str = str_replace("union", "", $str);
                $str = str_replace("where", "", $str);
                $str = str_replace("insert", "", $str);
                $str = str_replace("delete", "", $str);
                $str = str_replace("update", "", $str);
                $str = str_replace("like", "", $str);
                $str = str_replace("drop", "", $str);
                $str = str_replace("create", "", $str);
                $str = str_replace("modify", "", $str);
                $str = str_replace("rename", "", $str);
                $str = str_replace("alter", "", $str);
                $str = str_replace("cas", "", $str);
                if (empty($str))
                        return false;
                return $str;
        }

        public static function cleanhtml($str) {
//过滤时默认保留html中的 < a><img > 标签

                $str = strip_tags($str);


                $search = array(
                    '@<script[^>]*?>.*?</script>@si', // Strip out javascript
                    '@<[\/\!]*?[^<>]*?>@si', // Strip out HTML tags*/
                    '@<style[^>]*?>.*?</style>@siU', // Strip style tags properly
                    '@<![\s\S]*?--[ \t\n\r]*>@'         // Strip multi - line comments including CDATA
                );
                $str = preg_replace($search, '', $str);


                $str = preg_replace("/\s+/", " ", $str); //过滤多余回车

                $str = preg_replace("/<[ ]+/si", "<", $str); //过滤 < __(" < "号后面带空格)

                $str = preg_replace("/<\!–.*?–>/si", "", $str); //注释

                $str = preg_replace("/<(\!.*?)>/si", "", $str); //过滤DOCTYPE

                $str = preg_replace("/<(\/?html.*?)>/si", "", $str); //过滤html标签

                $str = preg_replace("/<(\/?head.*?)>/si", "", $str); //过滤head标签

                $str = preg_replace("/<(\/?meta.*?)>/si", "", $str); //过滤meta标签

                $str = preg_replace("/<(\/?body.*?)>/si", "", $str); //过滤body标签

                $str = preg_replace("/<(\/?link.*?)>/si", "", $str); //过滤link标签

                $str = preg_replace("/<(\/?form.*?)>/si", "", $str); //过滤form标签

                $str = preg_replace("/cookie/si", "COOKIE", $str); //过滤COOKIE标签

                $str = preg_replace("/<(applet.*?)>(.*?)<(\/applet.*?)>/si", "", $str); //过滤applet标签

                $str = preg_replace("/<(\/?applet.*?)>/si", "", $str); //过滤applet标签

                $str = preg_replace("/<(style.*?)>(.*?)<(\/style.*?)>/si", "", $str); //过滤style标签

                $str = preg_replace("/<(\/?style.*?)>/si", "", $str); //过滤style标签



                $str = preg_replace("/<(title.*?)>(.*?)<(\/title.*?)>/si", "", $str); //过滤title标签

                $str = preg_replace("/<(\/?title.*?)>/si", "", $str); //过滤title标签

                $str = preg_replace("/<(object.*?)>(.*?)<(\/object.*?)>/si", "", $str); //过滤object标签

                $str = preg_replace("/<(\/?objec.*?)>/si", "", $str); //过滤object标签

                $str = preg_replace("/<(noframes.*?)>(.*?)<(\/noframes.*?)>/si", "", $str); //过滤nofra
                $str = preg_replace("/<(\/?noframes.*?)>/si", "", $str); //过滤noframes标签

                $str = preg_replace("/<(i?frame.*?)>(.*?)<(\/i?frame.*?)>/si", "", $str); //过滤frame标签

                $str = preg_replace("/<(\/?i?frame.*?)>/si", "", $str); //过滤frame标签

                $str = preg_replace("/<(script.*?)>(.*?)<(\/script.*?)>/si", "", $str); //过滤script标
                $str = preg_replace("/<(\/?script.*?)>/si", "", $str); //过滤script标签

                $str = preg_replace("/javascript/si", "Javascript", $str); //过滤script标签

                $str = preg_replace("/vbscript/si", "Vbscript", $str); //过滤script标签

                $str = preg_replace("/on([a-z]+)\s*=/si", "On\\1=", $str); //过滤script标签

                $str = preg_replace("/&#/si", "&＃", $str); //过滤script标签



                $str = preg_replace("@<script(.*?)</script>@is", "", $str);

                $str = preg_replace("@<iframe(.*?)</iframe>@is", "", $str);

                $str = preg_replace("@<style(.*?)</style>@is", "", $str);

                $str = preg_replace("@<(.*?)>@is", "", $str);




                return $str;
        }

        public static function getUserinfo($id = NULL, $Field = NULL) {






                if ($id == NULL) {
                        return FALSE;
                }


                $userDB = M('member_basic');


                $where['member_id'] = $id;





                if (isset($Field)) {

                        $fields = array('member_email', 'member_nickname', 'member_up_face', 'member_heat', 'member_articles', 'member_type', 'member_glinks');

                        if (in_array($Field, $fields)) {





                                $info = $userDB->where($where)->limit(1)->getField($Field);


                                return$info;
                        }
                } else {


                        return $info = $userDB->where($where)->limit(1)->find();
                }

//	
        }

        public static function addLoginRecord($uid = NULL, $type = 2) {


                if ($uid == NULL) {
                        return FALSE;
                }





                $login_recordDB = M('login_record');
                $data['record_member_id'] = $uid;
                $data['record_ip'] = get_client_ip();
                $data['record_os'] = 1;

//1pc  2wap

                $data['record_type'] = $type;

//0 自动登录 ，1 qq  2 账号登录 

                $data['record_time'] = time();


                if ($login_recordDB->add($data)) {

                        return TRUE;
                }

                return FALSE;
        }

        public static function getLastLogintime($uid) {



                if (!is_numeric($uid)) {

                        return FALSE;
                }


                $login_recordDB = M('login_record');



                $where['record_member_id'] = $uid;





                $data_time = $login_recordDB->where($where)->limit(1)->getField('record_time');

                return $data_time;
        }

        public static function getCateArticleNumbers($cate_id = NULL) {

                if ($cate_id == NULL || !is_numeric($cate_id)) {
                        return FALSE;
                }


                $aDB = M('article');



                $where['article_cate_id'] = $cate_id;


                return $aDB->where($where)->count();
        }

        public static function delnullArray($arr) {
                if (is_array($arr)) {
                        foreach ($arr as $key => $value) {
                                if (is_array($value) && empty($value)) {
                                        unset($arr[$key]);
                                } else {
                                        if (is_array($value)) {
                                                $arr[$key] = self::delnullArray($value);
                                        }
                                }
                        }
                }
                return $arr;
        }

        public static function myArraysort($arr, $keys, $type = 'asc') {
                $keysvalue = $new_array = array();
                foreach ($arr as $k => $v) {
                        $keysvalue[$k] = $v[$keys];
                }
                if ($type == 'asc') {
                        asort($keysvalue);
                } else {
                        arsort($keysvalue);
                }
                reset($keysvalue);
                foreach ($keysvalue as $k => $v) {
                        $new_array[$k] = $arr[$k];
                }
                return $new_array;
        }

//========分类处理======




        public static function sortOut($cate, $pid = 0, $level = 0, $html = '---') {
                $tree = array();
                foreach ($cate as $v) {
                        if ($v['cate_pid'] == $pid) {
                                $v['level'] = $level + 1;
                                $v['html'] = str_repeat($html, $level);
                                $tree[] = $v;
//根据父级id查找所有的子分类
                                $tree = array_merge($tree, self::sortOut($cate, $v['cate_id'], $level + 1, $html));
                        }
                }
                return $tree;
        }

        public static function doTree(&$list, $pid = 0, $level = 0, $html = '--') {
                static $tree = array();
                foreach ($list as $v) {
                        if ($v['cate_pid'] == $pid) {
                                $v['sort'] = $level;
                                $v['html'] = str_repeat($html, $level);
                                $tree[] = $v;
                                self::doTree($list, $v['id'], $level + 1);
                        }
                }
                return $tree;
        }

//获取某分类的直接子分类  
        public static function getSons($categorys, $catId = 0) {
                $sons = array();
                foreach ($categorys as $item) {
                        if ($item['cate_pid'] == $catId)
                                $sons[] = $item;
                }
                return $sons;
        }

//获取某个分类的所有子分类  
        public static function getSubs($categorys, $catId = 0, $level = 1) {
                $subs = array();
                foreach ($categorys as $item) {
                        if ($item['cate_pid'] == $catId) {
                                $item['level'] = $level;
                                $subs[] = $item;
                                $subs = array_merge($subs, self::getSubs($categorys, $item['cate_id'], $level + 1));
                        }
                }
                return $subs;
        }

//获取某个分类的所有父分类  
//方法一，递归  
        public static function getParents($categorys, $catId) {
                $tree = array();
                foreach ($categorys as $item) {
                        if ($item['cate_id'] == $catId) {
                                if ($item['cate_pid'] > 0)
                                        $tree = array_merge($tree, self::getParents($categorys, $item['cate_pid']));
                                $tree[] = $item;
                                break;
                        }
                }
                return $tree;
        }

//方法二,迭代  
        public static function getParents2($categorys, $catId) {
                $tree = array();
                while ($catId != 0) {
                        foreach ($categorys as $item) {
                                if ($item['categoryId'] == $catId) {
                                        $tree[] = $item;
                                        $catId = $item['parentId'];
                                        break;
                                }
                        }
                }
                return $tree;
        }

//================常见的验证类================



        public static function IS_Empty($val) {
                if (!is_string($val))
                        return false; //是否是字符串类型 

                if (empty($val))
                        return false; //是否已设定 

                if ($val == '')
                        return false; //是否为空 

                return true;
        }

        /*
          -----------------------------------------------------------
          函数名称：isNumber
          简要描述：检查输入的是否为数字
          输入：string
          输出：boolean
          修改日志：------
          -----------------------------------------------------------
         */

        public static function isNumber($val) {
                if (ereg("^[0-9]+$", $val))
                        return true;
                return false;
        }

        /*
          -----------------------------------------------------------
          函数名称：isPhone
          简要描述：检查输入的是否为电话
          输入：string
          输出：boolean
          修改日志：------
          -----------------------------------------------------------
         */

        public static function isPhone($val) {
//eg: xxx-xxxxxxxx-xxx | xxxx-xxxxxxx-xxx ... 
                if (ereg("^((0\d{2,3})-)(\d{7,8})(-(\d{3,}))?$", $val))
                        return true;
                return false;
        }

        /*
          -----------------------------------------------------------
          函数名称：isPostcode
          简要描述：检查输入的是否为邮编
          输入：string
          输出：boolean
          修改日志：------
          -----------------------------------------------------------
         */

        public static function isPostcode($val) {
                if (ereg("^[0-9]{4,6}$", $val))
                        return true;
                return false;
        }

        /*
          -----------------------------------------------------------
          函数名称：isEmail
          简要描述：邮箱地址合法性检查
          输入：string
          输出：boolean
          修改日志：------
          -----------------------------------------------------------
         */

        public static function isEmail($val, $domain = "") {
                if (!$domain) {
                        if (preg_match("/^[a-z0-9-_.]+@[\da-z][\.\w-]+\.[a-z]{2,4}$/i", $val)) {
                                return true;
                        } else
                                return false;
                }
                else {
                        if (preg_match("/^[a-z0-9-_.]+@" . $domain . "$/i", $val)) {
                                return true;
                        } else
                                return false;
                }
        }

//end func 

        /*
          -----------------------------------------------------------
          函数名称：isName
          简要描述：姓名昵称合法性检查，只能输入中文英文
          输入：string
          输出：boolean
          修改日志：------
          -----------------------------------------------------------
         */

        public static function isName($val) {
                if (preg_match("/^[\x80-\xffa-zA-Z0-9]{3,60}$/", $val)) {//2008-7-24 
                        return true;
                }
                return false;
        }

//end func 


        /*
          -----------------------------------------------------------
          函数名称:isStrLength($theelement, $min, $max)
          简要描述:检查字符串长度是否符合要求
          输入:mixed (字符串，最小长度，最大长度)
          输出:boolean
          修改日志:------
          -----------------------------------------------------------
         */

        public static function IsStrLength($val, $min, $max) {
                $theelement = trim($val);
                if (ereg("^[a-zA-Z0-9]{" . $min . "," . $max . "}$", $val))
                        return true;
                return false;
        }

        /*
          -----------------------------------------------------------
          函数名称:isNumberLength($theelement, $min, $max)
          简要描述:检查字符串长度是否符合要求
          输入:mixed (字符串，最小长度，最大长度)
          输出:boolean
          修改日志:------
          -----------------------------------------------------------
         */

        public static function isNumLength($val, $min, $max) {
                $theelement = trim($val);
                if (ereg("^[0-9]{" . $min . "," . $max . "}$", $val))
                        return true;
                return false;
        }

        /*
          -----------------------------------------------------------
          函数名称:isNumberLength($theelement, $min, $max)
          简要描述:检查字符串长度是否符合要求
          输入:mixed (字符串，最小长度，最大长度)
          输出:boolean
          修改日志:------
          -----------------------------------------------------------
         */

        public static function isEngLength($val, $min, $max) {
                $theelement = trim($val);
                if (ereg("^[a-zA-Z]{" . $min . "," . $max . "}$", $val))
                        return true;
                return false;
        }

        /*
          -----------------------------------------------------------
          函数名称：isEnglish
          简要描述：检查输入是否为英文
          输入：string
          输出：boolean
          作者：------
          修改日志：------
          -----------------------------------------------------------
         */

        public static function isEnglish($theelement) {
                if (ereg("[\x80-\xff].", $theelement)) {
                        Return false;
                }
                Return true;
        }

        public static function isChinese($sInBuf) {//正确的函数 
                if (preg_match("/^[\x7f-\xff]+$/", $sInBuf)) { //兼容gb2312,utf-8 
                        return true;
                } else {
                        return false;
                }
        }

        /*
          -----------------------------------------------------------
          函数名称:isDomain($Domain)
          简要描述:检查一个（英文）域名是否合法
          输入:string 域名
          输出:boolean
          修改日志:------
          -----------------------------------------------------------
         */

        public static function isDomain($Domain) {
                if (!eregi("^[0-9a-z]+[0-9a-z\.-]+[0-9a-z]+$", $Domain)) {
                        Return false;
                }
                if (!eregi("\.", $Domain)) {
                        Return false;
                }

                if (eregi("\-\.", $Domain) or eregi("\-\-", $Domain) or eregi("\.\.", $Domain) or eregi("\.\-", $Domain)) {
                        Return false;
                }

                $aDomain = explode(".", $Domain);
                if (!eregi("[a-zA-Z]", $aDomain[count($aDomain) - 1])) {
                        Return false;
                }

                if (strlen($aDomain[0]) > 63 || strlen($aDomain[0]) < 1) {
                        Return false;
                }
                Return true;
        }

        /**
         * 验证是否日期的函数
         * @param unknown_type $date
         * @param unknown_type $format
         * @throws Exception
         * @return boolean
         */
        public static function validateDate($date, $format = 'YYYY-MM-DD') {
                switch ($format) {
                        case 'YYYY/MM/DD':
                        case 'YYYY-MM-DD':
                                list( $y, $m, $d ) = preg_split('/[-./ ]/', $date);
                                break;

                        case 'YYYY/DD/MM':
                        case 'YYYY-DD-MM':
                                list( $y, $d, $m ) = preg_split('/[-./ ]/', $date);
                                break;

                        case 'DD-MM-YYYY':
                        case 'DD/MM/YYYY':
                                list( $d, $m, $y ) = preg_split('/[-./ ]/', $date);
                                break;

                        case 'MM-DD-YYYY':
                        case 'MM/DD/YYYY':
                                list( $m, $d, $y ) = preg_split('/[-./ ]/', $date);
                                break;

                        case 'YYYYMMDD':
                                $y = substr($date, 0, 4);
                                $m = substr($date, 4, 2);
                                $d = substr($date, 6, 2);
                                break;

                        case 'YYYYDDMM':
                                $y = substr($date, 0, 4);
                                $d = substr($date, 4, 2);
                                $m = substr($date, 6, 2);
                                break;

                        default:
                                throw new Exception("Invalid Date Format");
                }
                return checkdate($m, $d, $y);
        }

        /*
          -----------------------------------------------------------
          函数名称：isDate
          简要描述：检查日期是否符合0000-00-00
          输入：string
          输出：boolean
          修改日志：------
          -----------------------------------------------------------
         */

        public static function isDate($sDate) {
                if (ereg("^[0-9]{4}\-[][0-9]{2}\-[0-9]{2}$", $sDate)) {
                        Return true;
                } else {
                        Return false;
                }
        }

        /*
          -----------------------------------------------------------
          函数名称：isTime
          简要描述：检查日期是否符合0000-00-00 00:00:00
          输入：string
          输出：boolean
          修改日志：------
          -----------------------------------------------------------
         */

        public static function isTime($sTime) {
                if (ereg("^[0-9]{4}\-[][0-9]{2}\-[0-9]{2} [0-9]{2}:[0-9]{2}:[0-9]{2}$", $sTime)) {
                        Return true;
                } else {
                        Return false;
                }
        }

        /*
          -----------------------------------------------------------
          函数名称:isMoney($val)
          简要描述:检查输入值是否为合法人民币格式
          输入:string
          输出:boolean
          修改日志:------
          -----------------------------------------------------------
         */

        public static function isMoney($val) {
                if (ereg("^[0-9]{1,}$", $val))
                        return true;
                if (ereg("^[0-9]{1,}\.[0-9]{1,2}$", $val))
                        return true;
                return false;
        }

        /*
          -----------------------------------------------------------
          函数名称:isIp($val)
          简要描述:检查输入IP是否符合要求
          输入:string
          输出:boolean
          修改日志:------
          -----------------------------------------------------------
         */

        public static function isIp($val) {
                return(bool) ip2long($val);
        }

//----------------------------------------------------------------------------- 

        /**
         * 验证手机号
         * @param int $mobile
         */
        public static function valid_mobile($mobile) {
                if (strlen($mobile) != 11)
                        return false;
                if (preg_match('/13[0-9]\d{8}|15[0|1|2|3|5|6|7|8|9]\d{8}|18[0|5|6|7|8|9]\d{8}/', $mobile)) {
                        return true;
                } else {
                        return false;
                }
        }

        /**
         * 缩略图生成函数，最好使用GD2
         *
         * @param string $srcFile 要生成缩略图的文件
         * @param int $toW 缩略图宽度
         * @param int $toH 缩略图高度
         * @param string $toFile 缩略图文件
         */
        function ImageResize($srcFile, $toW, $toH, $toFile = "") {
                if ($toFile == "") {
                        $toFile = $srcFile;
                }
                $info = "";
                $data = GetImageSize($srcFile, $info);
                switch ($data[2]) {
                        case 1:
                                if (!function_exists("imagecreatefromgif")) {
//echo "你的GD库不能使用GIF格式的图片，请使用Jpeg或PNG格式！<a href='javascript:go(-1);'>返回</a>"; 
                                        return false;
                                }
                                $im = ImageCreateFromGIF($srcFile);
                                break;
                        case 2:
                                if (!function_exists("imagecreatefromjpeg")) {
//echo "你的GD库不能使用jpeg格式的图片，请使用其它格式的图片！<a href='javascript:go(-1);'>返回</a>"; 
                                        return false;
                                }
                                $im = ImageCreateFromJpeg($srcFile);
                                break;
                        case 3:
                                $im = ImageCreateFromPNG($srcFile);
                                break;
                }
                $srcW = ImageSX($im);
                $srcH = ImageSY($im);
                $toWH = $toW / $toH;
                $srcWH = $srcW / $srcH;
                if ($toWH <= $srcWH) {
                        $ftoW = $toW;
                        $ftoH = $ftoW * ($srcH / $srcW);
                } else {
                        $ftoH = $toH;
                        $ftoW = $ftoH * ($srcW / $srcH);
                }
                if ($srcW > $toW || $srcH > $toH) {
                        if (function_exists("imagecreatetruecolor")) {
                                @$ni = ImageCreateTrueColor($ftoW, $ftoH);
                                if ($ni)
                                        ImageCopyResampled($ni, $im, 0, 0, 0, 0, $ftoW, $ftoH, $srcW, $srcH);
                                else {
                                        $ni = ImageCreate($ftoW, $ftoH);
                                        ImageCopyResized($ni, $im, 0, 0, 0, 0, $ftoW, $ftoH, $srcW, $srcH);
                                }
                        } else {
                                $ni = ImageCreate($ftoW, $ftoH);
                                ImageCopyResized($ni, $im, 0, 0, 0, 0, $ftoW, $ftoH, $srcW, $srcH);
                        }
                        if (function_exists('imagejpeg'))
                                ImageJpeg($ni, $toFile);
                        else
                                ImagePNG($ni, $toFile);
                        ImageDestroy($ni);
                }else {
                        ImageDestroy($im);
                        return false;
                }
                ImageDestroy($im);
                return true;
        }

//去除字符串空格 
        static function strTrim($str) {
                return preg_replace("/\s/", "", $str);
        }

//验证用户名 
        static function userName($str, $type, $len) {
                $str = self::strTrim($str);
                if ($len < strlen($str)) {
                        return false;
                } else {
                        switch ($type) {
                                case "EN"://纯英文 
                                        if (preg_match("/^[a-zA-Z]+$/", $str)) {
                                                return true;
                                        } else {
                                                return false;
                                        }
                                        break;
                                case "ENNUM"://英文数字 
                                        if (preg_match("/^[a-zA-Z0-9]+$/", $str)) {
                                                return true;
                                        } else {
                                                return false;
                                        }
                                        break;
                                case "ALL":    //允许的符号(|-_字母数字) 
                                        if (preg_match("/^[\|\-\_a-zA-Z0-9]+$/", $str)) {
                                                return true;
                                        } else {
                                                return false;
                                        }
                                        break;
                        }
                }
        }

//验证密码长度 
        static function passWord($min, $max, $str) {
                $str = self::strTrim($str);
                if (strlen($str) >= $min && strlen($str) <= $max) {
                        return true;
                } else {
                        return false;
                }
        }

//验证Email 
        static function Email($str) {
                $str = self::strTrim($str);

                if (preg_match("/^([a-z0-9_]|\\-|\\.)+@(([a-z0-9_]|\\-)+\\.){1,2}[a-z]{2,4}$/i", $str)) {
                        return true;
                } else {
                        return false;
                }
        }

//验证身份证(中国) 
        static function idCard($str) {
                $str = self::strTrim($str);
                if (preg_match("/^([0-9]{15}|[0-9]{17}[0-9a-z])$/i", $str)) {
                        return true;
                } else {
                        return false;
                }
        }

//验证座机电话 
        static function Phone($type, $str) {
                $str = self::strTrim($str);
                switch ($type) {
                        case "CHN":
                                if (preg_match("/^([0-9]{3}|0[0-9]{3})-[0-9]{7,8}$/", $str)) {
                                        return true;
                                } else {
                                        return false;
                                }
                                break;
                        case "INT":
                                if (preg_match("/^[0-9]{4}-([0-9]{3}|0[0-9]{3})-[0-9]{7,8}$/", $str)) {
                                        return true;
                                } else {
                                        return false;
                                }
                                break;
                }
        }

        /**
         * 过滤二维数组的值
         * @param 二维数组 $arr_data
         * @param 一维数组 $field
         * @return Ambigous <multitype:, string, unknown>
         */
        function getarrayfield($arr_data, $field) {
                $resultArr = array();
                foreach ($arr_data as $key => $value) {
                        foreach ($field as $k => $v) {
                                if (array_key_exists($v, $value)) {//存在才添加 
                                        $resultArr[$key][$v] = $value[$v];
                                } else {
                                        $resultArr[$key][$v] = "不存在这个列";
                                }
                        }
                }

                return $resultArr;
        }

        /**
         * 获取客户端IP地址
         * @return ip
         */
        function get_client_ip() {
                if (getenv("HTTP_CLIENT_IP") && strcasecmp(getenv("HTTP_CLIENT_IP"), "unknown"))
                        $ip = getenv("HTTP_CLIENT_IP");
                else if (getenv("HTTP_X_FORWARDED_FOR") && strcasecmp(getenv("HTTP_X_FORWARDED_FOR"), "unknown"))
                        $ip = getenv("HTTP_X_FORWARDED_FOR");
                else if (getenv("REMOTE_ADDR") && strcasecmp(getenv("REMOTE_ADDR"), "unknown"))
                        $ip = getenv("REMOTE_ADDR");
                else if (isset($_SERVER['REMOTE_ADDR']) && $_SERVER['REMOTE_ADDR'] && strcasecmp($_SERVER['REMOTE_ADDR'], "unknown"))
                        $ip = $_SERVER['REMOTE_ADDR'];
                else
                        $ip = "unknown";
                return($ip);
        }

        function get_http_user_agent() {
                return isset($_SERVER['HTTP_USER_AGENT']) ? $_SERVER['HTTP_USER_AGENT'] : "";
        }

        /**
         * 从IP地址获取真实地址
         * @param IP $ip
         */
        function get_address_from_ip($ip) {
                $url = 'http://www.youdao.com/smartresult-xml/search.s?type=ip&q=';
                $xml = file_get_contents($url . $ip);
                $data = simplexml_load_string($xml);
                return $data->product->location;
        }

        /**
         * 产生随机字串，可用来自动生成密码 默认长度6位 字母和数字混合
         * @param string $len 长度
         * @param string $type 字串类型
         * 0 字母 1 数字 2 大写字母 3 小写字母 默认混合 4中文
         * @param string $addChars 额外字符
         * @return string
         */
        function rand_string($len = 6, $type = '', $addChars = '') {
                $str = '';
                switch ($type) {
                        case 0:
                                $chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz' . $addChars;
                                break;
                        case 1:
                                $chars = str_repeat('0123456789', 3);
                                break;
                        case 2:
                                $chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' . $addChars;
                                break;
                        case 3:
                                $chars = 'abcdefghijklmnopqrstuvwxyz' . $addChars;
                                break;
                        case 4:
                                $chars = "们以我到他会作时要动国产的一是工就年阶义发成部民可出能方进在了不和有大这主中人上为来分生对于学下级地个用同行面说种过命度革而多子后自社加小机也经力线本电高量长党得实家定深法表着水理化争现所二起政三好十战无农使性前等反体合斗路图把结第里正新开论之物从当两些还天资事队批点育重其思与间内去因件日利相由压员气业代全组数果期导平各基或月毛然如应形想制心样干都向变关问比展那它最及外没看治提五解系林者米群头意只明四道马认次文通但条较克又公孔领军流入接席位情运器并飞原油放立题质指建区验活众很教决特此常石强极土少已根共直团统式转别造切九你取西持总料连任志观调七么山程百报更见必真保热委手改管处己将修支识病象几先老光专什六型具示复安带每东增则完风回南广劳轮科北打积车计给节做务被整联步类集号列温装即毫知轴研单色坚据速防史拉世设达尔场织历花受求传口断况采精金界品判参层止边清至万确究书术状厂须离再目海交权且儿青才证低越际八试规斯近注办布门铁需走议县兵固除般引齿千胜细影济白格效置推空配刀叶率述今选养德话查差半敌始片施响收华觉备名红续均药标记难存测士身紧液派准斤角降维板许破述技消底床田势端感往神便贺村构照容非搞亚磨族火段算适讲按值美态黄易彪服早班麦削信排台声该击素张密害侯草何树肥继右属市严径螺检左页抗苏显苦英快称坏移约巴材省黑武培著河帝仅针怎植京助升王眼她抓含苗副杂普谈围食射源例致酸旧却充足短划剂宣环落首尺波承粉践府鱼随考刻靠够满夫失包住促枝局菌杆周护岩师举曲春元超负砂封换太模贫减阳扬江析亩木言球朝医校古呢稻宋听唯输滑站另卫字鼓刚写刘微略范供阿块某功套友限项余倒卷创律雨让骨远帮初皮播优占死毒圈伟季训控激找叫云互跟裂粮粒母练塞钢顶策双留误础吸阻故寸盾晚丝女散焊功株亲院冷彻弹错散商视艺灭版烈零室轻血倍缺厘泵察绝富城冲喷壤简否柱李望盘磁雄似困巩益洲脱投送奴侧润盖挥距触星松送获兴独官混纪依未突架宽冬章湿偏纹吃执阀矿寨责熟稳夺硬价努翻奇甲预职评读背协损棉侵灰虽矛厚罗泥辟告卵箱掌氧恩爱停曾溶营终纲孟钱待尽俄缩沙退陈讨奋械载胞幼哪剥迫旋征槽倒握担仍呀鲜吧卡粗介钻逐弱脚怕盐末阴丰雾冠丙街莱贝辐肠付吉渗瑞惊顿挤秒悬姆烂森糖圣凹陶词迟蚕亿矩康遵牧遭幅园腔订香肉弟屋敏恢忘编印蜂急拿扩伤飞露核缘游振操央伍域甚迅辉异序免纸夜乡久隶缸夹念兰映沟乙吗儒杀汽磷艰晶插埃燃欢铁补咱芽永瓦倾阵碳演威附牙芽永瓦斜灌欧献顺猪洋腐请透司危括脉宜笑若尾束壮暴企菜穗楚汉愈绿拖牛份染既秋遍锻玉夏疗尖殖井费州访吹荣铜沿替滚客召旱悟刺脑措贯藏敢令隙炉壳硫煤迎铸粘探临薄旬善福纵择礼愿伏残雷延烟句纯渐耕跑泽慢栽鲁赤繁境潮横掉锥希池败船假亮谓托伙哲怀割摆贡呈劲财仪沉炼麻罪祖息车穿货销齐鼠抽画饲龙库守筑房歌寒喜哥洗蚀废纳腹乎录镜妇恶脂庄擦险赞钟摇典柄辩竹谷卖乱虚桥奥伯赶垂途额壁网截野遗静谋弄挂课镇妄盛耐援扎虑键归符庆聚绕摩忙舞遇索顾胶羊湖钉仁音迹碎伸灯避泛亡答勇频皇柳哈揭甘诺概宪浓岛袭谁洪谢炮浇斑讯懂灵蛋闭孩释乳巨徒私银伊景坦累匀霉杜乐勒隔弯绩招绍胡呼痛峰零柴簧午跳居尚丁秦稍追梁折耗碱殊岗挖氏刃剧堆赫荷胸衡勤膜篇登驻案刊秧缓凸役剪川雪链渔啦脸户洛孢勃盟买杨宗焦赛旗滤硅炭股坐蒸凝竟陷枪黎救冒暗洞犯筒您宋弧爆谬涂味津臂障褐陆啊健尊豆拔莫抵桑坡缝警挑污冰柬嘴啥饭塑寄赵喊垫丹渡耳刨虎笔稀昆浪萨茶滴浅拥穴覆伦娘吨浸袖珠雌妈紫戏塔锤震岁貌洁剖牢锋疑霸闪埔猛诉刷狠忽灾闹乔唐漏闻沈熔氯荒茎男凡抢像浆旁玻亦忠唱蒙予纷捕锁尤乘乌智淡允叛畜俘摸锈扫毕璃宝芯爷鉴秘净蒋钙肩腾枯抛轨堂拌爸循诱祝励肯酒绳穷塘燥泡袋朗喂铝软渠颗惯贸粪综墙趋彼届墨碍启逆卸航衣孙龄岭骗休借" . $addChars;
                                break;
                        case 5:
                                $chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789' . $addChars;
                                break;
                        default :
// 默认去掉了容易混淆的字符oOLl和数字01，要添加请使用addChars参数 
                                $chars = 'ABCDEFGHIJKMNPQRSTUVWXYZabcdefghijkmnpqrstuvwxyz23456789' . $addChars;
                                break;
                }
                if ($len > 10) {//位数过长重复字符串一定次数 
                        $chars = $type == 1 ? str_repeat($chars, $len) : str_repeat($chars, 5);
                }

                if ($type == 4) { // 处理中文 
                        $chars = preg_replace('/[^\\x{4e00}-\\x{9fa5}]/u', '', $chars);   // //干掉非utf8中文字符 
                        $chars = chunk_split($chars, 3, ","); // //每隔3个字符插入一个“,”，转换为数组使用，使用strlen()测出php中一个中文霸占了3个 
                        $re = explode(",", $chars);
                        shuffle($re); //随机重新排序数组 
                        $chars = implode($re);
                        unset($re);
                        $str = mb_substr($chars, 0, $len, "utf-8");
                } else {
                        $chars = str_shuffle($chars);
                        $str = substr($chars, 0, $len);
                }

                return $str;
        }

//获取url中参数的值 
        function geturlval($url, $name) {
                $arr = parse_url($url);
                $arr_query = $this->convertUrlQuery($arr['query']);

                return $arr_query[$name];
        }

        function convertUrlQuery($query) {
                $queryParts = explode('&', $query);

                $params = array();
                foreach ($queryParts as $param) {
                        $item = explode('=', $param);
                        $params[$item[0]] = $item[1];
                }

                return $params;
        }

        /**
         * 抓取远程图片
         *
         * @param string $url 远程图片路径
         * @param string $filename 本地存储文件名
         */
        public static function grabImage($url, $savepath) {
                if ($url == "") {
                        return false; //如果 $url 为空则返回 false; 
                }
                $ext_name = strrchr($url, '.'); //获取图片的扩展名 
                if ($ext_name != '.gif' && $ext_name != '.jpg' && $ext_name != '.bmp' && $ext_name != '.png') {
                        return false; //格式不在允许的范围 
                }
//获取原图片名 
                $filename = $savepath . '\\' . end(explode('/', $url));
//开始捕获 
                ob_start();
                readfile($url);
                $img_data = ob_get_contents();
                ob_end_clean();
                $size = strlen($img_data);
                $local_file = fopen($filename, 'a');
                echo $filename;
                if (fwrite($local_file, $img_data) == FALSE) {
                        echo '图片下载失败';
                }
                fclose($local_file);
                return $filename;
        }

//处理远程的复制的图片
        public static function getRemotePic($url, $savepath, $imgfile) {

                $ch = curl_init();
// $headers['User-Agent']='Mozilla/5.0 (Macintosh; Intel Mac OS X 10.9; rv:33.0) Gecko/20100101 Firefox/33.0';
                $headerArr = array('User-Agent:Mozilla/5.0 (Macintosh; Intel Mac OS X 10.9; rv:33.0) Gecko/20100101 Firefox/33.0');
                curl_setopt($ch, CURLOPT_URL, $url);
                curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
//curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
                curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // 跳过证书检查
                curl_setopt($ch, CURLOPT_HTTPHEADER, $headerArr);

                $img = curl_exec($ch);
//获取下载的类型 ，NULL表示服务器没有发送有效的Content-Type: header
                $type = curl_getinfo($ch, CURLINFO_CONTENT_TYPE);

                curl_close($ch);




                if ($img) {
                        if ($type) {
                                $type = substr($type, strrpos($type, '/') + 1);
                        } else {
                                $type = '';
                        }
                        file_put_contents($savepath . $imgfile . '.' . $type, $img);
                        return $imgfile . '.' . $type;
                } else {
                        return false;
                }
        }

        public static function getwebcontent($url) {
                $ch = curl_init();
                $timeout = 10;
                curl_setopt($ch, CURLOPT_URL, $url);
                curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
                curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
                curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
                $contents = trim(curl_exec($ch));
                curl_close($ch);
                return $contents;
        }

}

?>